﻿namespace System.ServiceModel.DomainServices.Client
{
    using System;
    using System.ComponentModel;

    public abstract class OperationBase : INotifyPropertyChanged
    {
        private bool _canceled;
        private bool _completed;
        private EventHandler _completedEventHandler;
        private Exception _error;
        private bool _isErrorHandled;
        private object _result;
        private object _userState;

        public event EventHandler Completed
        {
            add
            {
                if (this.IsComplete)
                {
                    value(this, EventArgs.Empty);
                }
                else
                {
                    this._completedEventHandler = (EventHandler) Delegate.Combine(this._completedEventHandler, value);
                }
            }
            remove
            {
                this._completedEventHandler = (EventHandler) Delegate.Remove(this._completedEventHandler, value);
            }
        }

        event PropertyChangedEventHandler PropertyChanged;

        protected OperationBase(object userState)
        {
            this._userState = userState;
        }

        public void Cancel()
        {
            if (!this.SupportsCancellation)
            {
                throw new NotSupportedException(Resources.AsyncOperation_CancelNotSupported);
            }
            this.EnsureNotCompleted();
            this._completed = true;
            this._canceled = true;
            this.CancelCore();
            this.InvokeCompleteAction();
            if (this._completedEventHandler != null)
            {
                this._completedEventHandler(this, EventArgs.Empty);
            }
            this.RaisePropertyChanged("IsCanceled");
            this.RaisePropertyChanged("CanCancel");
            this.RaisePropertyChanged("IsComplete");
        }

        protected virtual void CancelCore()
        {
        }

        protected void Complete(Exception error)
        {
            if (error == null)
            {
                throw new ArgumentNullException("error");
            }
            this.EnsureNotCompleted();
            bool canCancel = this.CanCancel;
            this._error = error;
            this._completed = true;
            this.InvokeCompleteAction();
            if (this._completedEventHandler != null)
            {
                this._completedEventHandler(this, EventArgs.Empty);
            }
            this.RaisePropertyChanged("Error");
            this.RaisePropertyChanged("HasError");
            this.RaisePropertyChanged("IsComplete");
            if (canCancel)
            {
                this.RaisePropertyChanged("CanCancel");
            }
            if (!this.IsErrorHandled)
            {
                throw error;
            }
        }

        protected void Complete(object result)
        {
            this.EnsureNotCompleted();
            bool canCancel = this.CanCancel;
            this._result = result;
            this._completed = true;
            this.InvokeCompleteAction();
            if (this._completedEventHandler != null)
            {
                this._completedEventHandler(this, EventArgs.Empty);
            }
            this.RaisePropertyChanged("IsComplete");
            if (canCancel)
            {
                this.RaisePropertyChanged("CanCancel");
            }
        }

        private void EnsureNotCompleted()
        {
            if (this._completed)
            {
                throw new InvalidOperationException(Resources.AsyncOperation_AlreadyCompleted);
            }
        }

        protected abstract void InvokeCompleteAction();
        public void MarkErrorAsHandled()
        {
            if (this._error == null)
            {
                throw new InvalidOperationException(Resource.Operation_HasErrorMustBeTrue);
            }
            if (!this._isErrorHandled)
            {
                this._isErrorHandled = true;
                this.RaisePropertyChanged("IsErrorHandled");
            }
        }

        protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (this._propChangedHandler != null)
            {
                this._propChangedHandler(this, e);
            }
        }

        protected void RaisePropertyChanged(string propertyName)
        {
            this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        }

        public bool CanCancel
        {
            get
            {
                return (this.SupportsCancellation && !this._completed);
            }
        }

        public Exception Error
        {
            get
            {
                return this._error;
            }
        }

        public bool HasError
        {
            get
            {
                return (this._error != null);
            }
        }

        public bool IsCanceled
        {
            get
            {
                return this._canceled;
            }
        }

        public bool IsComplete
        {
            get
            {
                return this._completed;
            }
        }

        public bool IsErrorHandled
        {
            get
            {
                return this._isErrorHandled;
            }
        }

        protected object Result
        {
            get
            {
                return this._result;
            }
        }

        protected virtual bool SupportsCancellation
        {
            get
            {
                return false;
            }
        }

        public object UserState
        {
            get
            {
                return this._userState;
            }
        }
    }
}

